/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.satish.gmailapp.servlets;

import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeCallbackServlet;
import com.satish.gmailapp.beans.User;
import static com.satish.gmailapp.constants.WebConstants.*;
import com.satish.gmailapp.service.GmailService;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author satish
 */
public class GoogleAuthCallbackServlet extends AbstractAuthorizationCodeCallbackServlet {
    private static final Logger logger = LogManager.getLogger(GoogleAuthCallbackServlet.class);

    @Override
    protected void onSuccess(HttpServletRequest req, HttpServletResponse resp, Credential credential) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        User user = new User();
        user.setLoggedIn();
        user.setCredential(credential);
        session.setAttribute(USER, user);
        final String redirectUri = (String)session.getAttribute(REDIRECT_URI);
        logger.debug("REDIRECT_URI: " + redirectUri);
        resp.sendRedirect(redirectUri);
    }

    @Override
    protected void onError(HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse) throws ServletException, IOException {
        req.getRequestDispatcher("/faces/error.xhtml").forward(req, resp);
    }

    @Override
    protected AuthorizationCodeFlow initializeFlow() throws ServletException, IOException {
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        GmailService gmailService = (GmailService) context.getBean("gmailService");
        return gmailService.getGoogleAuthorizationCodeFlow();
    }

    @Override
    protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
        return req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/googleAuthCallback";
    }

    @Override
    protected String getUserId(HttpServletRequest hsr) throws ServletException, IOException {
        return "temp";
    }
}
